package com.link.play.fit.ai.ui.view;

import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SnapHelper;

public class SevenItemPagerSnapHelper extends SnapHelper {
    private RecyclerView recyclerView;

    @Override
    public void attachToRecyclerView(@Nullable RecyclerView recyclerView) throws IllegalStateException {
        super.attachToRecyclerView(recyclerView);
        this.recyclerView = recyclerView;
    }

    @Override
    public int[] calculateDistanceToFinalSnap(
            @NonNull RecyclerView.LayoutManager layoutManager,
            @NonNull View targetView
    ) {
        if (layoutManager instanceof LinearLayoutManager) {
            int pageWidth = recyclerView.getWidth();
            int currentPosition = layoutManager.getPosition(targetView);
            int pageIndex = currentPosition / 7;
            int targetScrollX = pageIndex * pageWidth;
            int currentScrollX = getCurrentScrollX();
            return new int[]{targetScrollX - currentScrollX, 0};
        }
        return new int[]{0, 0};
    }

    @Override
    public View findSnapView(RecyclerView.LayoutManager layoutManager) {
        if (layoutManager instanceof LinearLayoutManager) {
            int firstVisiblePos = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition();
            int pageIndex = firstVisiblePos / 7;
            return layoutManager.findViewByPosition(pageIndex * 7);
        }
        return null;
    }

    @Override
    public int findTargetSnapPosition(
            RecyclerView.LayoutManager layoutManager,
            int velocityX,
            int velocityY
    ) {
        if (layoutManager instanceof LinearLayoutManager) {
            int currentPosition = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition();
            int pageIndex = currentPosition / 7;
            // 根据滑动速度判断翻页方向
            if (velocityX > 0) pageIndex++;
            else if (velocityX < 0) pageIndex--;
            // 确保页码有效
            int maxPage = (layoutManager.getItemCount() - 1) / 7;
            pageIndex = Math.max(0, Math.min(pageIndex, maxPage));
            return pageIndex * 7;
        }
        return RecyclerView.NO_POSITION;
    }

    private int getCurrentScrollX() {
        return recyclerView.computeHorizontalScrollOffset();
    }
}